import logging
import logging.handlers
import os
import sys
import json
import threading
import socket



START_EXE_PATH  = os.path.abspath(sys.argv[0])
START_BASE_PATH = os.path.dirname(START_EXE_PATH)
START_EXE_LOG   = os.path.join(START_BASE_PATH, "log")



class ConfigS(object):
    def __init__(self):
        self.lock = threading.Lock()
        self.CFG = { }
        self.path_file = os.path.join(START_BASE_PATH, "config.json")
        if os.path.exists(self.path_file):
            self.read_json()
        else:
            self.CFG = {
                "folder_path": START_BASE_PATH,
                "static_path": os.path.join(START_BASE_PATH, "web"),
                "description": "用户共享目录",
                "port": 1122,
                "wlip": "192.168.50.179",
                "wlport": 6789
            }
            self._save_file()
    
    def _save_file(self):
        with open(self.path_file, "w", encoding="utf-8") as f:
            json.dump(self.CFG, f, ensure_ascii=False, indent=4)

    def save_json(self, item, typ="set"):
        try:
            with self.lock:
                if typ == "set":
                    self.CFG.update({item["key"]: item["value"]})
                elif typ == "del":
                    if item in self.CFG:
                        self.CFG.pop(item)
                self._save_file()        
                return True
        except Exception as e:
            err_log(e)
            return False

    def read_json(self):
        try:
            with open(self.path_file, "r", encoding="utf-8") as f:
                self.CFG = json.load(f)
        except Exception as e:
            err_log(e)
            self.CFG = { }



def err_log(e):
    frame = sys._getframe(1)
    file_name = frame.f_code.co_filename
    line_number = frame.f_lineno
    call_name = frame.f_code.co_name
    error_logger = logging.getLogger('error_logger')
    error_logger.error("错误文件: {} 错误行数: {} 错误函数: {} 数据类型: {} 数据输出: {}".format(file_name, line_number, call_name, type(e), e))



def custom_err_log(*args):
    error_logger = logging.getLogger('error_logger')
    error_logger.error(' '.join(str(arg) for arg in args))


def info_log(*args):
    error_logger = logging.getLogger('error_logger')
    error_logger.info(' '.join(str(arg) for arg in args))


def get_ip_address():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except Exception:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP




os.makedirs(START_EXE_LOG, exist_ok=True)

handler = logging.handlers.TimedRotatingFileHandler(os.path.join(START_EXE_LOG, "error_log.log"), when='midnight', interval=1, backupCount=100, delay=True)
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
handler.setLevel(logging.ERROR)

logging.getLogger('error_logger').addHandler(handler)

CONFIG = ConfigS()

IPADDR = get_ip_address()

